<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>

    <th:block th:include="include :: header('目标检测数据集列表')"/>
    <link rel="stylesheet" href="/fontawesome-free-6.4.0-web/css/all.min.css">
    <script src="/sweetalert2-11.12.2/sweetalert2@11.js"></script>
    <script src="/axios/axios.min.js"></script>

    <style>
        .status-btn {
            display: inline-block;
            padding: 1px 20px;
            margin: 0px;
            margin-top: 5px;
            background-color: #5bc0de; /* 可以根据需要调整颜色 */
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .status-btn:hover {
            background-color: #31b0d5; /* 悬停时的颜色变化 */
        }

        .pageBtn {
            background-color: #007bff; /* 蓝色背景 */
            color: white; /* 白色文字 */
            border: none;
            padding: 5px 10px; /* 内边距 */
            margin: 0 5px; /* 按钮之间的间距 */
            border-radius: 4px; /* 圆角边框 */
            cursor: pointer;
        }

        #jumpBtn {
            background-color: #28a745; /* 绿色背景 */
            color: white; /* 白色文字 */
            border: none;
            padding: 5px 10px; /* 内边距 */
            margin: 0 5px; /* 按钮之间的间距 */
            border-radius: 4px; /* 圆角边框 */
            cursor: pointer;
        }

        .pageBtn:hover, #jumpBtn:hover {
            background-color: #0056b3; /* 深蓝色 */
        }

        #jumpContainer {
            margin-top: 10px; /* 跳转框的间距 */
            text-align: center; /* 中心对齐 */
        }

    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            数据集名称：<input type="text" name="name"/>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                    class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>


        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="detection:detectionDataset:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <li>
                <!--                通过点击按钮来切换显示的数据集状态-->
                <a class="status-btn" data-status="self">仅自己</a>
                <a class="status-btn" data-status="all">全部</a>
            </li>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table" class="table table-bordered" data-mobile-responsive="true"></table>
        </div>
    </div>
</div>
<div th:include="include :: footer"></div>

<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('detection:detectionDataset:edit')}]];
    var removeFlag = [[${@permission.hasPermi('detection:detectionDataset:remove')}]];
    var prefix = ctx + "detection/detectionDataset";
    var isAdmin = false;
    var url = null;
    var userId = -1;
    var status = "self";
    var options = null;

    // axios请求/getUserRole下的/userId
    axios.get("/getUserRole/getUserId")
        .then(function (response) {
            console.log("请求成功，获取到用户id：", response.data);
            axios.get("/getUserRole/isAdmin")
                .then(function (response) {  // 这里的右括号应该去掉
                    console.log("请求成功，获取到是否是管理员：", response.data);
                    isAdmin = response.data;
                    if (isAdmin) {
                        console.log("是管理员，可以查看全部数据集");
                    } else {
                        console.log("不是管理员，只能查看自己的数据集");
                    }
                })
                .catch(function (error) {
                    console.error("请求出错：", error.response ? error.response.data : error.message);
                });
            userId = response.data;
            url = prefix + "/list?userId=" + userId;
            $(function () {
                console.log("url:", url)
                options = {
                    url: url,
                    createUrl: prefix + "/add",
                    updateUrl: prefix + "/edit/{id}",
                    removeUrl: prefix + "/remove",
                    exportUrl: prefix + "/export",
                    modalName: "目标检测数据集",
                    showExport: true,
                    columns: [
                        {
                            field: 'id',
                            title: 'id',
                            visible: false
                        },
                        {
                            field: 'name',
                            title: '数据集名称',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'userName',
                            title: '归属用户',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'numTrain',
                            title: '图片数量',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'numVall',
                            title: '标签数量',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'height',
                            title: '高',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'width',
                            title: '宽',
                            align: 'center',
                            sortable: true
                        },
                        {
                            field: 'uploadTime',
                            title: '上传时间',
                            align: 'center',
                            sortable: true
                        },

                        // {
                        //     field: 'isPublic',
                        //     title: '是否公开',
                        //     align: 'center'
                        // },
                        {
                            title: '操作',
                            align: 'center',
                            formatter: function (value, row, index) {
                                var actions = [];
                                if (isAdmin) {
                                    actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                                    // actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                                    actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick=deleteDataset(\'' + row.id + '\')><i class="fa fa-remove"></i>删除</a>');
                                    actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick=showImg(\'' + row.location + '\')><i class="fa fa-eye"></i>查看</a>'); // 新增的“查看”按钮
                                    return actions.join(' ');
                                } else {
                                    if (row.userId === userId) {
                                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick=showImg(\'' + row.location + '\')><i class="fa fa-eye"></i>查看</a>'); // 新增的“查看”按钮
                                        return actions.join(' ');
                                    } else {
                                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick=showImg(\'' + row.location + '\')><i class="fa fa-eye"></i>查看</a>'); // 新增的“查看”按钮
                                        return actions.join(' ');
                                    }
                                }

                            }
                        }]
                };
                $.table.init(options);
            });
        })
        .catch(function (error) {
            console.error("请求出错：", error.response ? error.response.data : error.message);
        });

    $(".status-btn").click(function () {
        status = $(this).data("status");
        console.log("status:", status)
        if (status === "self") {
            console.log("切换到仅自己的数据集");
            url = prefix + "/list?userId=" + userId;
            // console.log("url:", url)
            options.url = url;
        } else {
            console.log("切换到全部的数据集");
            url = prefix + "/list";
            // console.log("url:", url)
            options.url = url;
        }
        $.table.destroy()
        // $.table.refresh({url: url});
        $.table.init(options);
    });

    function deleteDataset(id) {
        console.log("删除数据集id:", id)
        $.modal.confirm("确定删除该条" + $.table._option.modalName + "信息吗？", function () {
            var url = $.common.isEmpty(id) ? $.table._option.removeUrl : $.table._option.removeUrl.replace("{id}", id);
            if ($.table._option.type == table_type.bootstrapTreeTable) {
                $.operate.post(url);

            } else {
                var data = {"ids": id};
                $.operate.submit(url, "post", "json", data);
                axios.post(prefix + "/delete/", {id: id})
                    .then(function (response) {
                        console.log("response:", response)
                        if (response.status === 200) {
                            console.log("删除成功：", response.data);
                            $.table.refresh();
                        }
                    })
                    .catch(function (error) {
                        console.log("删除失败：", error.response ? error.response.data : error.message)
                    });
            }
        });
    }

    async function showImg(location) {
        const targetLocation = location.split('/resources')[1];
        const images = await getImages(location + '/images');
        const labels = await getLabels(location + '/labels');

        let currentIndex = 0;
        const imagesPerRow = 5; // 每行展示的图片数量
        const rowsPerPage = 3; // 每页展示的行数

        const uniqueClasses = new Set();

        // 收集所有类别
        const numberOfClasses = uniqueClasses.size;
        const colorMap = {};

        // 自动生成颜色
        const generateColor = (index) => {
            const numberOfClasses = uniqueClasses.size; // 动态获取类别数量
            const hue = (index * 360) / numberOfClasses; // 计算色调
            return `hsl(${hue}, 100%, 50%)`;
        };


        const showImages = (index) => {
            const start = index * imagesPerRow * rowsPerPage;
            const end = Math.min(start + imagesPerRow * rowsPerPage, images.length);
            const imageHtml = [];

            for (let i = start; i < end; i++) {
                const imgPath = `${targetLocation}images/${images[i]}`;
                const labelFileName = images[i].replace(/\.jpg$/, '.txt');
                const labelPath = `${targetLocation}labels/${labelFileName}`;
                const canvasId = `canvas${i}`;

                imageHtml.push(`
                <div style="flex: 0 1 calc(20% - 5px); margin: 2px;">
                    <canvas id="${canvasId}" style="max-width: 100%; max-height: 200px;"></canvas>
                </div>
            `);

                const imageElement = new Image();
                let annotations = null;
                if (labels[i] !== undefined) {
                    fetch(labelPath)
                        .then(response => {
                            if (response.ok) {
                                return response.text();
                            } else {
                                throw new Error("标签文件不存在");
                            }
                        })
                        .then(labelContent => {
                            // console.log("labelContent:", labelContent)
                            annotations = labelContent.split('\n').map(parseAnnotation).filter(Boolean);
                            console.log("annotations:", annotations)
                            // 更新 uniqueClasses 和 colorMap
                            annotations.forEach(ann => {
                                uniqueClasses.add(ann.classId);
                                if (!colorMap[ann.classId]) {
                                    colorMap[ann.classId] = generateColor(uniqueClasses.size - 1);
                                }
                            });

                            const canvas = document.getElementById(canvasId);
                            const ctx = canvas.getContext('2d');


                            imageElement.onload = function () {
                                canvas.width = imageElement.width;
                                canvas.height = imageElement.height;
                                ctx.clearRect(0, 0, canvas.width, canvas.height);
                                ctx.drawImage(imageElement, 0, 0);

                                if (annotations) {
                                    annotations.forEach(ann => {
                                        const labelId = ann.classId;
                                        // console.log("labelId:", labelId)
                                        const x = (ann.centerX - ann.width / 2) * imageElement.width;
                                        const y = (ann.centerY - ann.height / 2) * imageElement.height;
                                        const boxWidth = ann.width * imageElement.width;
                                        const boxHeight = ann.height * imageElement.height;

                                        // 获取对应的颜色
                                        ctx.strokeStyle = colorMap[labelId] || 'red'; // 默认颜色
                                        ctx.lineWidth = 5;
                                        ctx.strokeRect(x, y, boxWidth, boxHeight);

                                        // 添加点击事件来放大图片
                                        canvas.onclick = () => {
                                            showLargeImage(imgPath, annotations, colorMap); // 传递注释和颜色映射
                                        };

                                        // 显示类型文本
                                        ctx.fillStyle = colorMap[labelId] || 'black'; // 确保文本颜色与矩形框一致
                                        ctx.font = '16px Arial';
                                        ctx.fillText(`Type: ${labelId}`, x, y > 10 ? y - 5 : 10); // 确保文本不超出画布
                                    });
                                }
                            };


                            imageElement.src = imgPath;
                        })
                        .catch(error => {
                            const canvas = document.getElementById(canvasId);
                            const ctx = canvas.getContext('2d');
                            imageElement.onload = function () {
                                canvas.width = imageElement.width;
                                canvas.height = imageElement.height;
                                ctx.clearRect(0, 0, canvas.width, canvas.height);
                                ctx.drawImage(imageElement, 0, 0);

                                if (annotations) {
                                    annotations.forEach(ann => {
                                        const labelId = ann.classId;
                                        const x = (ann.centerX - ann.width / 2) * imageElement.width;
                                        const y = (ann.centerY - ann.height / 2) * imageElement.height;
                                        const boxWidth = ann.width * imageElement.width;
                                        const boxHeight = ann.height * imageElement.height;

                                        // 获取对应的颜色
                                        ctx.strokeStyle = colorMap[labelId] || 'black'; // 默认颜色为黑色
                                        ctx.lineWidth = 5;
                                        ctx.strokeRect(x, y, boxWidth, boxHeight);

                                        // 添加点击事件来放大图片
                                        canvas.onclick = () => {
                                            showLargeImage(imgPath, annotations, colorMap); // 传递注释和颜色映射
                                        };

                                        // 显示类型文本
                                        ctx.fillStyle = colorMap[labelId] || 'black'; // 确保文本颜色与矩形框一致
                                        ctx.font = '16px Arial';
                                        ctx.fillText(`Type: ${labelId}`, x, y > 10 ? y - 5 : 10); // 确保文本不超出画布
                                    });
                                }
                            };

                            imageElement.src = imgPath;
                        });
                } else {
                    console.log("执行else分支")
                    imageElement.onload = function () {
                        const canvas = document.getElementById(canvasId);
                        const ctx = canvas.getContext('2d');

                        canvas.width = imageElement.width;
                        canvas.height = imageElement.height;
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        ctx.drawImage(imageElement, 0, 0);

                        // 添加点击事件来放大图片
                        canvas.onclick = () => {
                            showLargeImage(imgPath, annotations, colorMap); // 传递注释和颜色映射
                        };
                    };
                    imageElement.src = imgPath;
                }
            }
            console.log("uniqueClasses:",uniqueClasses)
            console.log("colorMap:",colorMap)

            return `
            <div style="display: flex; flex-wrap: wrap; justify-content: center;">
                ${imageHtml.join('')}
            </div>
        `;
        };

        // 放大图片的函数
        const showLargeImage = (imgPath, annotations, colorMap) => {
            const overlay = document.createElement('div');
            overlay.style.position = 'fixed';
            overlay.style.top = 0;
            overlay.style.left = 0;
            overlay.style.width = '100%';
            overlay.style.height = '100%';
            overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            overlay.style.display = 'flex';
            overlay.style.justifyContent = 'center';
            overlay.style.alignItems = 'center';
            overlay.style.zIndex = 9999;

            const img = document.createElement('img');
            img.src = imgPath;
            img.style.maxWidth = '90%';
            img.style.maxHeight = '90%';
            img.style.border = '2px solid white';

            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = img.naturalWidth;
            canvas.height = img.naturalHeight;

            // 绘制图像
            img.onload = () => {
                ctx.drawImage(img, 0, 0);
                // 绘制注释
                annotations.forEach(ann => {
                    const labelId = ann.classId;
                    const x = (ann.centerX - ann.width / 2) * canvas.width;
                    const y = (ann.centerY - ann.height / 2) * canvas.height;
                    const boxWidth = ann.width * canvas.width;
                    const boxHeight = ann.height * canvas.height;

                    ctx.strokeStyle = colorMap[labelId] || 'black';
                    ctx.lineWidth = 5;
                    ctx.strokeRect(x, y, boxWidth, boxHeight);
                    ctx.fillStyle = colorMap[labelId] || 'black';
                    ctx.font = '16px Arial';
                    ctx.fillText(`Type: ${labelId}`, x, y > 10 ? y - 5 : 10);
                });
            };

            // 创建关闭按钮
            const closeButton = document.createElement('button');
            closeButton.innerText = '×';
            closeButton.style.position = 'absolute';
            closeButton.style.top = '10%';
            closeButton.style.right = '10%';
            closeButton.style.fontSize = '50px';
            closeButton.style.color = 'white';
            closeButton.style.background = 'none';
            closeButton.style.border = 'none';
            closeButton.style.cursor = 'pointer';

            closeButton.onclick = (event) => {
                event.stopPropagation();
                document.body.removeChild(overlay);
            };

            // 点击overlay关闭放大图片
            overlay.onclick = () => {
                document.body.removeChild(overlay);
            };

            overlay.appendChild(closeButton);
            overlay.appendChild(canvas);
            document.body.appendChild(overlay);
        };


        const updatePaginationButtons = () => {
            const totalPages = Math.ceil(images.length / (imagesPerRow * rowsPerPage));
            const maxButtons = 5; // 最多显示的按钮数量
            let buttonsHtml = '';

            const startPage = Math.max(0, currentIndex - 2);
            const endPage = Math.min(totalPages - 1, startPage + maxButtons - 1);

            // 添加第一页按钮
            if (startPage > 0) {
                buttonsHtml += `<button class="pageBtn" data-page="0">1</button>`;
                if (startPage > 1) {
                    buttonsHtml += `<span>...</span>`;
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                buttonsHtml += `<button class="pageBtn" data-page="${i}">${i + 1}</button>`;
            }

            // 添加最后一页按钮
            if (endPage < totalPages - 1) {
                if (endPage < totalPages - 2) {
                    buttonsHtml += `<span>...</span>`;
                }
                buttonsHtml += `<button class="pageBtn" data-page="${totalPages - 1}">${totalPages}</button>`;
            }

            document.getElementById('paginationContainer').innerHTML = buttonsHtml;

            // 更新上一页和下一页按钮的状态
            document.getElementById('prevBtn').disabled = currentIndex === 0;
            document.getElementById('nextBtn').disabled = (currentIndex + 1) * imagesPerRow * rowsPerPage >= images.length;

            // 更新页面信息
            document.getElementById('pageInfo').innerText = `第 ${currentIndex + 1} 页 / 共 ${totalPages} 页`;

            const pageButtons = document.querySelectorAll('.pageBtn');
            pageButtons.forEach(button => {
                button.onclick = () => {
                    currentIndex = parseInt(button.dataset.page);
                    document.getElementById('imageContainer').innerHTML = showImages(currentIndex);
                    updatePaginationButtons();
                };
            });
        };


        const bindPaginationButtons = () => {
            document.getElementById('prevBtn').onclick = () => {
                if (currentIndex > 0) {
                    currentIndex--;
                    document.getElementById('imageContainer').innerHTML = showImages(currentIndex);
                    updatePaginationButtons();
                }
            };

            document.getElementById('nextBtn').onclick = () => {
                if ((currentIndex + 1) * imagesPerRow * rowsPerPage < images.length) {
                    currentIndex++;
                    document.getElementById('imageContainer').innerHTML = showImages(currentIndex);
                    updatePaginationButtons();
                }
            };
        };

        // 打开模态框并显示第一组图片
        Swal.fire({
            title: '查看图片',
            html: `
            <div id="imageContainer" style="max-height: 70vh; overflow-y: auto;">
                ${showImages(currentIndex)}
            </div>
            <div style="text-align: center; margin-top: 10px;">
                <button id="prevBtn" disabled>上一页</button>
                <button id="nextBtn" disabled>下一页</button>
                <input type="number" id="pageInput" min="1" max="${Math.ceil(images.length / (imagesPerRow * rowsPerPage))}" placeholder="跳转到页码" style="width: 100px; margin-left: 10px;">
                <button id="jumpBtn">跳转</button>
            </div>
            <div id="paginationContainer" style="text-align: center; margin-top: 10px;"></div>
            <div id="pageInfo" style="text-align: center; margin-top: 10px;">第 1 页 / 共 ${Math.ceil(images.length / (imagesPerRow * rowsPerPage))} 页</div>
        `,
            showCloseButton: true,
            // 关闭按钮内容为OK
            confirmButtonText: '关闭',
            width: '90%',
            padding: '10px',
            didOpen: () => {
                updatePaginationButtons();
                bindPaginationButtons();

                // 跳转按钮事件
                document.getElementById('jumpBtn').onclick = () => {
                    const pageInput = document.getElementById('pageInput');
                    const pageNumber = parseInt(pageInput.value) - 1; // 转换为0基索引
                    if (pageNumber >= 0 && pageNumber < Math.ceil(images.length / (imagesPerRow * rowsPerPage))) {
                        currentIndex = pageNumber;
                        document.getElementById('imageContainer').innerHTML = showImages(currentIndex);
                        updatePaginationButtons();
                    } else {
                        // Swal.fire({
                        //     title: '错误',
                        //     text: '请输入有效的页码！',
                        //     icon: 'error',
                        //     confirmButtonText: '确定'
                        // });
                        // alert("请输入有效的页码！");
                    }
                };
            }
        });
    }

    function parseAnnotation(line) {
        const parts = line.split(' ');
        return {
            classId: parseInt(parts[0]),
            centerX: parseFloat(parts[1]),
            centerY: parseFloat(parts[2]),
            width: parseFloat(parts[3]),
            height: parseFloat(parts[4]),
        };
    }


    function getImages(path) {
        return axios.get(prefix + "/getImages?path=" + encodeURIComponent(path))
            .then(response => {
                const files = response.data;
                // console.log("图片列表：", files);
                return files;
            })
            .catch(error => {
                console.error("获取图片列表失败：", error);
                return [];
            });
    }

    function getLabels(path) {
        return axios.get(prefix + "/getLabels?path=" + encodeURIComponent(path))
            .then(response => {
                const files = response.data;
                // console.log("标注文件列表：", files);
                return files;
            })
            .catch(error => {
                console.error("获取标注文件列表失败：", error);
                return [];
            });
    }


</script>


</body>
</html>